import axios from 'axios'
import qs from 'qs'
import { baseurl } from './constants'
import {ElMessage} from 'element-plus'
class Request {
  http = axios.create({
    baseURL: baseurl,
    timeout: 60000,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  });

  request({ url, method = 'GET', params = {}, isMock }) {
    return new Promise((resolve, reject) => {
      method = method.toLowerCase();
      const requestBody = method === 'get' ? 'params' : 'data';
      const format = method === 'get' ? params : qs.stringify(params);
      isMock ? this.http.defaults.baseURL = '' : this.http.defaults.baseURL = baseurl;

      const result = this.http({ url, method, [requestBody]: format});
      result.then(value => resolve(value.data), reason => process.env.NODE_ENV === 'production'? console.log(reason) : ElMessage.error(JSON.stringify(reason)) );
    });
  }
  
}

export default new Request()